/**
 * 
 */
package com.vivid.dynamics.oknow.dao.impl;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vivid.dynamics.oknow.dao.IUserDAO;
import com.vivid.dynamics.oknow.dao.IUserThemeDAO;
import com.vivid.dynamics.oknow.model.User;

/**
 *
 * @author jason
 * created at:: Jul 29, 2011 10:43:16 AM
 */
public class UserDAOImpl implements IUserDAO {

	static Logger logger=Logger.getLogger(UserDAOImpl.class);
	
	private @Autowired SessionFactory sessionFactory;
	
	/**
	 * {@inheritDoc}
	 * @see com.vivid.dynamics.oknow.dao.IUserDAO#getUserByKey(int)
	 */
	@Override
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public User getUserByKey(int pId) {
		Session aSession=this.sessionFactory.getCurrentSession();
		User aUser=null;
		
		aUser=(User) aSession.get(User.class, Integer.valueOf(pId));
		
		return aUser;
	}

// TODO: extract it to Manager class... later
	private @Autowired IUserThemeDAO userThemeDAO;
	
	/**
	 * {@inheritDoc}
	 * @see com.vivid.dynamics.oknow.dao.IUserDAO#newUser(com.vivid.dynamics.oknow.model.User)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public Serializable newUser(User pUser) {
		Session aSession=this.sessionFactory.getCurrentSession();
		Serializable aKey=null;
		
		if (pUser!=null) {
// TODO: extract this part of validation in the Manager level instead of DAO level~ Plus use IoC instead of direct creation of DAO
			/*
			 * check whether the userTheme itself is valid or not
			 */
			if (pUser.getUserTheme()==null || pUser.getUserTheme().getId()<=0) {
				
				
				pUser.setUserTheme(userThemeDAO.getUserThemeByKey(com.vivid.dynamics.oknow.config.spring.Constants.DEFAULT_USER_THEME.intValue()));
			}
			aKey=aSession.save(pUser);
			if (logger.isDebugEnabled()) {
				logger.debug("[newUser] Key :: "+aKey);
			}
		}
		return aKey;
	}

	/**
	 * {@inheritDoc}
	 * @see com.vivid.dynamics.oknow.dao.IUserDAO#updateUser(com.vivid.dynamics.oknow.model.User)
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void updateUser(User pUser) {
		Session aSession=this.sessionFactory.getCurrentSession();
		
		if (pUser!=null) {
			aSession.update(pUser);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteUser(User pUser) {
		Session aSession=this.sessionFactory.getCurrentSession();
		if (pUser!=null) {
			aSession.delete(pUser);
		}
	}

}
